import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DbUtils1 {
    private static DruidDataSource ds;
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();
    static {
        Properties properties = new Properties();
        InputStream is = DbUtils.class.getClassLoader().getResourceAsStream("jdbc1.properties");
        try {
            properties.load(is);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        //获取链接
        public static Connection getConnection(){
            Connection connection = THREAD_LOCAL.get();
            try {
                if (connection == null) {
                    connection = ds.getConnection();
                    THREAD_LOCAL.set(connection);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            return connection;
        }
        public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                    THREAD_LOCAL.remove();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
